package com.yantong.controller.statistics;



import com.yantong.constant.PermisFlag;
import com.yantong.controller.BaseController;
import com.yantong.result.ResultVo;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.excel.ExcelHelper;
import com.yantong.service.OrderService;
import com.yantong.service.StatisticsCommanderService;
import com.yantong.pojo.vo.*;
import com.yantong.pojo.ListMemberParams;
import com.yantong.pojo.Member;
import com.yantong.mapper.MemberMapper;
import com.yantong.service.CommanderListService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 门店商品统计
 *
 * @author xiangyi
 * @version V1.0.0
 * @date 2018年9月14日 上午11:53:59
 * @since 3.0
 */
@Controller
@RequestMapping("/statistics/commander")
public class CommanderCommodityController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CommanderCommodityController.class);

    private static final String prefix = "statistics/commander";
    private static final String prefix2 = "statistics/sale";
    private static final String prefix3 = "statistics/achievement";
    @Autowired
    private StatisticsCommanderService statisticsCommanderService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CommanderListService commanderListService;

    /**
     * 门店商品统计界面
     *
     * @return
     */
    @GetMapping()
    @RequiresPermissions("statistics:commander:commodity")
    public String commanderCommodity(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/commanderCommodity";
    }


    /**
     * 门店商品销售统计
     *
     * @param listMemberParams
     * @param member
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("statistics:commander:commodity")
    public PageUtils<Member> commanderCommodityStatistics(ListMemberParams listMemberParams, Member member, int offset, int limit) {
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        return statisticsCommanderService.commanderCommodityStatistics(listMemberParams, member, offset, limit);
    }

    /**
     * 商品交易总量
     *
     * @param listMemberParams
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("/getJyTotal")
    @RequiresPermissions("statistics:commander:commodity")
    public Long getJyTotal(ListMemberParams listMemberParams, Member member) {
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        return statisticsCommanderService.getJyTotal(listMemberParams, member);
    }

    /**
     * 导出
     *
     * @param response
     * @param listMemberParams
     * @param member
     */
    @RequiresPermissions("statistics:commander:export")
    @GetMapping("/exportStatistics")
    public void exportStatistics(HttpServletResponse response, ListMemberParams listMemberParams, Member member) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"序号", "门店姓名", "门店名称", "交易量", "所占比例"};
        resultData.add(0, Arrays.asList(head));
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        List<Member> list = statisticsCommanderService.statisticsExport(listMemberParams, member);
        if (CollectionUtils.isNotEmpty(list)) {
            int n = 1;
            for (Member mem : list) {
                List<Object> row = new ArrayList<>();
                row.add(n);
                row.add(mem.getRealname() != null ? mem.getRealname() : "");
                row.add(mem.gettXiaoqu() != null ? mem.gettXiaoqu() : "");
                row.add(mem.getAlltotal() != null ? mem.getAlltotal() : "");
                row.add(mem.getScale() != null ? mem.getScale() + "%" : "");
                resultData.add(row);
                n++;
            }
            String fileName = "门店商品销量统计_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
            try {
                ExcelHelper.exportExcel(response, fileName, "门店商品销量统计", resultData);
            } catch (IOException e) {
                logger.info("exportStatistics error:{}", e.getMessage());
            }
        }
    }


    /**
     * 跳转  门店单品销售统计
     */
    @GetMapping("/toStoreItemSalesStats")
    public String toStoreItemSalesStats(Model model, Integer tMid) {
        model.addAllAttributes(getTeamIdList(null));
        model.addAttribute("tMid", tMid);
        return prefix2 + "/storeItemSalesStats";
    }

    /**
     * 门店单品销售统计
     */
    @ResponseBody
    @GetMapping("/getStoreItemSalesStats")
    public PageUtils<StoreSalesStatsVo> getStoreItemSalesStats(DataStatsDto dataStatsDto) {
        dataStatsDto.setQueryType(1);
        List<StoreSalesStatsVo> storeSalesStatsVoList = statisticsCommanderService.getStoreItemSalesStats(dataStatsDto);
        PageUtils<StoreSalesStatsVo> pageUtils = new PageUtils<>();
        pageUtils.setRows(storeSalesStatsVoList);
        pageUtils.setTotal(storeSalesStatsVoList.size());

        return pageUtils;
    }

    /**
     * 跳转  门店销售统计
     */
    @GetMapping("/toStoreSalesStats")
    public String toStoreSalesStats(Model model) {

        model.addAllAttributes(getTeamIdList(null));

        return prefix2 + "/storeSalesStats";
    }

    /**
     * 门店销售统计
     */
    @ResponseBody
    @GetMapping("/getStoreSalesStats")
    public PageUtils<StoreSalesStatsVo> getStoreSalesStats(DataStatsDto dataStatsDto) {

        dataStatsDto.setQueryType(2);

        List<StoreSalesStatsVo> storeSalesStatsVoList = statisticsCommanderService.getStoreItemSalesStats(dataStatsDto);
        PageUtils<StoreSalesStatsVo> pageUtils = new PageUtils<>();
        pageUtils.setRows(storeSalesStatsVoList);
        pageUtils.setTotal(storeSalesStatsVoList.size());

        return pageUtils;
    }

    /**
     * 跳转  门店商品销售详细
     */
    @GetMapping("/toStoreCommoditySalesInfo")
    public String toStoreCommoditySalesInfo(Model model) {
        model.addAllAttributes(getTeamIdList(null));

        return prefix2 + "/storeCommoditySalesInfo";
    }

    /**
     * 门店商品销售详细
     */
    @ResponseBody
    @GetMapping("/getStoreCommoditySalesInfo")
    public PageUtils<StoreSalesStatsVo> getStoreCommoditySalesInfo(DataStatsDto dataStatsDto) {

        dataStatsDto.setQueryType(3);

        List<StoreSalesStatsVo> storeSalesStatsVoList = statisticsCommanderService.getStoreItemSalesStats(dataStatsDto);
        PageUtils<StoreSalesStatsVo> pageUtils = new PageUtils<>();
        pageUtils.setRows(storeSalesStatsVoList);
        pageUtils.setTotal(storeSalesStatsVoList.size());

        return pageUtils;

    }

//    /**
//     * 跳转  门店销售历史统计
//     */
//    @GetMapping("/toStoreSalesHistoryStats")
//    public String toStoreSalesHistoryStats(Model model){
//
//        model.addAllAttributes(getTeamIdList(null));
//
//        return prefix2+"/storeSalesHistoryStats";
//    }
//    /**
//     * 门店销售历史统计
//     */
//    @ResponseBody
//    @GetMapping("/getStoreSalesHistoryStats")
//    public void getStoreSalesHistoryStats(){
//
//    }

    /**
     * 门店销售总金额，总销量 统计
     */
    @ResponseBody
    @PostMapping("/getStoreItemSalesStatsSum")
    public ResultVo getStoreItemSalesStatsSum(DataStatsDto dataStatsDto) {

        StoreSalesStatsVo storeSalesStatsVo = statisticsCommanderService.getStoreItemSalesStatsSum(dataStatsDto);

        return ResultVo.ok().put("data", storeSalesStatsVo);
    }


    ////////////////////

    /**
     * 用户  业绩统计  跳转
     *
     * @return
     */
    @GetMapping("/toUserAchievementStats")
    public String toUserAchievementStats() {

        return prefix3 + "/userAchievementStats";
    }

    /**
     * 用户  业绩统计
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getUserAchievementStats")
    public PageUtils<UserAchievementVo> getUserAchievementStats(DataStatsDto dataStatsDto) {

        Integer num = statisticsCommanderService.getUserachievementDataCount(dataStatsDto);
        PageUtils<UserAchievementVo> pageUtils = new PageUtils<>();
        if (num <= 0) {
            return pageUtils;
        }
        List<UserAchievementVo> userAchievementVoList = statisticsCommanderService.getUserachievementData(dataStatsDto,
                new RowBounds(dataStatsDto.getOffset(), dataStatsDto.getLimit()));
        List<Long> idList = new ArrayList<>();
        for (UserAchievementVo model : userAchievementVoList) {
            idList.add(model.getId());
        }
        Map mapP = new HashMap();
        mapP.put("mids", idList);
        Map<Long, OrderAchievementVo> selfMap = statisticsCommanderService.getUserSelfStats(mapP);
        Map<Long, OrderAchievementVo> shareMap = statisticsCommanderService.getUserShareStats(mapP);
        for (UserAchievementVo model : userAchievementVoList) {
            BigDecimal selfPayprice = BigDecimal.ZERO;
            OrderAchievementVo selfVo = selfMap.get(model.getId());
            if (selfVo != null) {
                selfPayprice = selfVo.getPayprice();
            }
            BigDecimal sharePayprice = BigDecimal.ZERO;
            OrderAchievementVo shareVo = shareMap.get(model.getId());
            if (shareVo != null) {
                sharePayprice = shareVo.getPayprice();
            }
            if (model.getIsteam() != null && model.getIsteam() == 3) {
                model.setIsteamStr("创客");
            } else {
                model.setIsteamStr("普通用户");
            }
            model.setSelfAchievement(selfPayprice);
            model.setShareAchievement(sharePayprice);
            model.setSumAchievement(selfPayprice.add(sharePayprice));
        }

        pageUtils.setRows(userAchievementVoList);
        pageUtils.setTotal(num);

        return pageUtils;
    }

    @GetMapping("/toTeamAchievementStats")
    public String toTeamAchievementStats(Model model) {
        model.addAllAttributes(getTeamIdList(null));
        return prefix3 + "/teamAchievementStats";
    }

    /**
     * 门店  业绩统计
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getTeamAchievementStats")
    public PageUtils<UserAchievementVo> getTeamAchievementStats(DataStatsDto dataStatsDto) {
        List<UserAchievementVo> userAchievementVoList = statisticsCommanderService.getTeamAchievementStats(dataStatsDto);
        BigDecimal sumPrice = BigDecimal.ZERO;
        for (UserAchievementVo model : userAchievementVoList) {
            sumPrice = sumPrice.add(model.getPrice());
        }
        PageUtils<UserAchievementVo> pageUtils = new PageUtils<>();

        pageUtils.setRows(userAchievementVoList);
        pageUtils.setTotal(userAchievementVoList.size());
        return pageUtils;
    }

    @GetMapping("/toRoleAchievementStats")
    public String toRoleAchievementStats() {
        return prefix3 + "/roleAchievementStats";
    }

    @GetMapping("/toRoleAchievementStats_2")
    public String toRoleAchievementStats_2() {
        return prefix3 + "/roleAchievementStats_2";
    }

    @GetMapping("/toRoleAchievementStats_3")
    public String toRoleAchievementStats_3() {
        return prefix3 + "/roleAchievementStats_3";
    }

    @ResponseBody
    @GetMapping("/getRoleAchievementStats")
    public PageUtils<UserAchievementVo> getRoleAchievementStats(DataStatsDto dataStatsDto) {

        Map<Integer, UserAchievementVo> dataMap = new LinkedHashMap<>();

        List<UserAchievementVo> userAchievementVoList = statisticsCommanderService.getRoleAchievementStats(dataStatsDto);
        for (UserAchievementVo model : userAchievementVoList) {
            if (model.getIsteam() != null && model.getIsteam() == 3) {
                model.setIsteamStr("创客");
            } else {
                model.setIsteamStr("普通用户");
            }
            UserAchievementVo userAchievementVo = dataMap.get(model.getRoleMid());
            if (userAchievementVo == null) {
                userAchievementVo = model;
                userAchievementVo.addMidNum(1);
                if (userAchievementVo.getIsteam() == 3) {
                    userAchievementVo.addTeamNum(1);
                }
                dataMap.put(userAchievementVo.getRoleMid(), userAchievementVo);
            } else {
                userAchievementVo.addPrice(model.getPrice());
                userAchievementVo.addMidNum(1);
                if (userAchievementVo.getIsteam() == 3) {
                    userAchievementVo.addTeamNum(1);
                }
            }
        }
        List<UserAchievementVo> list = new ArrayList<UserAchievementVo>(dataMap.values());

        PageUtils<UserAchievementVo> pageUtils = new PageUtils<>();

        pageUtils.setRows(list);
        pageUtils.setTotal(dataMap.size());
        return pageUtils;
    }

    @GetMapping("/toCentreAchievementStats")
    public String toCentreAchievementStats(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix3 + "/centreAchievementStats";
    }

    /**
     * 门店开户数统计
     *
     * @param dataStatsDto
     * @return
     */
    @ResponseBody
    @GetMapping("/getCentreAchievementStats")
    public PageUtils<UserAchievementVo> getCentreAchievementStats(DataStatsDto dataStatsDto) {

        List<UserAchievementVo> list = statisticsCommanderService.getCentreAchievementStats(dataStatsDto, new RowBounds(dataStatsDto.getOffset(), dataStatsDto.getLimit()));
        Integer num = statisticsCommanderService.getCentreAchievementStatsCount(dataStatsDto);
        PageUtils<UserAchievementVo> pageUtils = new PageUtils<>();

        if (num == 0) {
            return pageUtils;
        }
        pageUtils.setRows(list);
        pageUtils.setTotal(num);
        return pageUtils;

    }

    @GetMapping("/storeVerifyStats")
    public String storeVerifyStats(Model model) {
        return prefix + "/storeVerifyStats";
    }

    /**
     * 门店优惠券核销统计
     */
    @ResponseBody
    @GetMapping("/getStoreVerifyStats")
    public PageUtils<StoreVerifyStatsVo> getStoreVerifyStats() {
        List<StoreVerifyStatsVo> list = new ArrayList<>();
        if (PermisFlag.FLAG_CENTRE.equals(getUserFlag())) {
            //商户帐号，只查询总店的店员核销数据
            Member member = memberMapper.selectByCentreIdAndIsHeadOffice(getUserCentreId(), 1);
            if (member != null) {
                list = statisticsCommanderService.getStoreVerifyStats(member.getId());
            }
        } else if (PermisFlag.FLAG_SHOP.equals(getUserFlag())) {
            //门店帐号，查询自己门店的店员核销数据
            list = statisticsCommanderService.getStoreVerifyStats(getUserTeamId());
        }
        PageUtils<StoreVerifyStatsVo> pageUtils = new PageUtils<>();
        pageUtils.setRows(list);
        pageUtils.setTotal(list == null ? 0 : list.size());
        return pageUtils;
    }

    @GetMapping("/storeVerifyStatsDetail")
    public String storeVerifyStatsDetail(Model model) {
        ListMemberParams listMemberParams = new ListMemberParams();
        if (getUserCentreId() != null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        List<Member> teams = commanderListService.listCommanders(listMemberParams, new Member());
        model.addAttribute("teams", teams);

        if (PermisFlag.FLAG_SHOP.equals(getUserFlag())) {
            //门店帐号，查询自己门店的店员核销数据
            model.addAttribute("teamId", getUserTeamId());
        }

        return prefix + "/storeVerifyStatsDetail";
    }

    /**
     * 门店优惠券核销明细统计
     */
    @ResponseBody
    @GetMapping("/getStoreVerifyStatsDetail")
    public PageUtils<StoreVerifyStatsVo> getStoreVerifyStatsDetail(String start, String end, String day, Long teamId) {
        List<StoreVerifyStatsVo> list = new ArrayList<>();
        Map map = new HashMap();

        if (teamId != null) {
            map.put("selectedTeamId", teamId);
        }

        if (null != DateUtils.parseDateForm(day)) {
            Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
            ca.setTime(DateUtils.parseDateForm(day)); //设置时间为当前时间
            ca.set(Calendar.HOUR_OF_DAY, 0);
            ca.set(Calendar.MINUTE, 0);
            ca.set(Calendar.SECOND, 0);
            map.put("start", ca.getTime());
            ca.set(Calendar.HOUR_OF_DAY, 23);
            ca.set(Calendar.MINUTE, 59);
            ca.set(Calendar.SECOND, 59);
            map.put("end", ca.getTime());
        } else if (null != start && null != end) {
            map.put("start", start);
            map.put("end", end);
        }
        if (PermisFlag.FLAG_CENTRE.equals(getUserFlag())) {
            //商户帐号，只查询总店的店员核销数据
            Member member = memberMapper.selectByCentreIdAndIsHeadOffice(getUserCentreId(), 1);
            if (member != null) {
                map.put("teamId", member.getId());
                list = statisticsCommanderService.getStoreVerifyStatsDetail(map);
            }
        } else if (PermisFlag.FLAG_SHOP.equals(getUserFlag())) {
            //门店帐号，查询自己门店的店员核销数据
            map.put("teamId", getUserTeamId());
            list = statisticsCommanderService.getStoreVerifyStatsDetail(map);
        }

        String remark = "";
        if (null != day) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            remark = "归属日期:" + day;
        } else if (null != DateUtils.parseDateForm(start) && null != DateUtils.parseDateForm(end)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            remark = "查询区间:" + start + "--" + end;
        }
        if (!list.isEmpty()) {
            for (StoreVerifyStatsVo storeVerifyStatsVo : list) {
                storeVerifyStatsVo.setRemark(remark);
            }
        }

        PageUtils<StoreVerifyStatsVo> pageUtils = new PageUtils<>();
        pageUtils.setRows(list);
        pageUtils.setTotal(list == null ? 0 : list.size());
        return pageUtils;
    }
}
